<template>
	<view>
		<!--index.wxml-->
		<view class="container">
			<map id="map" :longitude="longitude" :latitude="latitude" scale="14" :markers="markers" :polyline="polyline"
			 :enable-satellite="satellite" show-location style="width: 100%; height: 100vh;"></map>
		</view>
	</view>




	</view>
</template>

<script>
	export default {
		components: {},


		computed: {

		},
		data() {
			return {
				markers: [], // 标记点集合
				polyline: [], // 坐标点集合
				satellite: true, // 是否开启卫星图
				i: 0, // 用于循环
				latitude: 39.806466,
				longitude: 98.226473,
			};
		},
		onReady: function() {
			this.mapCtx = wx.createMapContext('map'); // 创建 map 上下文 MapContext 对象
		},
		onLoad: function() {
			let that = this;

			// 获取当前坐标
			uni.getLocation({
				type: 'wgs84',
				success: (res) => {
					
					// 坐标集合
					let points = [{
						longitude: res.longitude,
						latitude: res.latitude
					}, {
						longitude: res.longitude + 0.03,
						latitude: res.latitude + 0.03
					}, {
						longitude: res.longitude - 0.01,
						latitude: res.latitude + 0.02
					}, {
						longitude: res.longitude - 0.01,
						latitude: res.latitude + 0.01
					}, {
						longitude: res.longitude,
						latitude: res.latitude
					}];
					// 标记点集合
					let markers = points;
					markers.map((value, index) => {
						markers[index].id = index + 1;
					});

					that.polyline = [{
						points: points,
						color: "#FF0000DD",
						width: 2
					}];
					that.markers = markers;
					that.latitude = res.latitude;
					that.longitude = res.longitude;

					this.translateMarker(markers);
				}
			})
		},
		onShow: function() {
			let that = this;
		},
		watch: {

		},
		methods: {
			// 平移marker，带动画
			translateMarker: function(markers) {
				let that = this;
				let markerId = markers[that.i].id;
				let destination = {
					longitude: markers[that.i + 1].longitude,
					latitude: markers[that.i + 1].latitude
				};
				let getDistance = that.getDistance(markers[that.i].latitude, markers[that.i].longitude, markers[that.i + 1].latitude,
					markers[that.i + 1].longitude);
				let duration = getDistance * 2; // 根据距离计算平移的速度，看起来保持匀速
				this.mapCtx.translateMarker({
					markerId: markerId,
					destination: destination,
					autoRotate: true,
					rotate: 30,
					duration: duration,
					success(res) {
						that.i = that.i + 1;

						// 小于长度减1才执行
						if (that.i < markers.length - 1) {
							that.translateMarker(markers);
						}
					},
					fail(err) {
						console.log('fail', err)
					}
				})
			},
			// 计算两坐标点之间的距离
			getDistance: function(lat1, lng1, lat2, lng2) {
				let rad1 = lat1 * Math.PI / 180.0;
				let rad2 = lat2 * Math.PI / 180.0;
				let a = rad1 - rad2;
				let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
				let r = 6378137;
				return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math
					.sin(b / 2), 2)))).toFixed(0)

			}

		},
	}
</script>

<style lang="scss">

</style>
